﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Net.Http.Headers;

namespace PesticideManage.API.Services.JWT;

public class AppJwtBearerEvents : JwtBearerEvents
{
    private readonly ILogger<AppJwtBearerEvents> _logger;

    public AppJwtBearerEvents(ILogger<AppJwtBearerEvents> logger)
    {
        _logger = logger;
    }
    /// <summary>
    /// 收到信息
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public override Task MessageReceived(MessageReceivedContext context)
    {
        // 从 Http Request Header 中获取 Authorization
        string? authorization = context.Request.Headers[HeaderNames.Authorization];
        //authorization ??= (context.Request.Query["token"].ToString());

        if (string.IsNullOrEmpty(authorization))
        {
            context.NoResult();
            return Task.CompletedTask;
        }

        // 必须为 Bearer 认证方案
        if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
        {
            // 赋值token
            context.Token = authorization["Bearer ".Length..].Trim();
        }

        if (string.IsNullOrEmpty(context.Token))
        {
            context.NoResult();
        }
        return Task.CompletedTask;
    }


    public override Task AuthenticationFailed(AuthenticationFailedContext context)
    {
        //Console.WriteLine($"Exception: {context.Exception}");
        _logger.LogError(context.Exception, $"Exception: {context.Exception.Message}");
        return Task.CompletedTask;
    }
    /// <summary>
    /// 质询
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public override Task Challenge(JwtBearerChallengeContext context)
    {
        _logger.LogError(context.AuthenticateFailure, $"Authenticate Failure: {context.AuthenticateFailure}");
        _logger.LogError($"Error: {context.Error}");
        _logger.LogError($"Error Description: {context.ErrorDescription}");
        _logger.LogError($"Error Uri: {context.ErrorUri}");
        // 添加标记，使前端知晓access token过期，可以使用refresh token了
        if (context.AuthenticateFailure is SecurityTokenExpiredException)
        {
            // context.Response.Headers.Add("Access-Control-Expose-Headers", "x-access-token");
            context.Response.Headers.Add("Expires", "expired");
            context.Response.Headers.Add("Shang", "expired");
            //context.Response.StatusCode = 401;
            //await context.Response.WriteAsync("Hello world!");
            // await context.Response.WriteAsJsonAsync(new { error = context.ErrorDescription });
        }

        return Task.CompletedTask;
    }

    public override Task Forbidden(ForbiddenContext context)
    {
        return base.Forbidden(context);
    }

    public override Task TokenValidated(TokenValidatedContext context)
    {
        return base.TokenValidated(context);
    }
}